import { Plugins, PluginType } from './index';
import { PluginValidator } from './validator';
import { PluginLifecycleManager, PluginLifecycleEvent, PluginState } from './lifecycle';
import { PluginMonitor } from './monitor';
import { TTSTestFramework } from './test-framework-tts';
import { PluginInterface, PluginImportOptions } from './defined/plugins';
import { Logger } from '../logger';
import { errorHandler } from '../utils';

/**
 * 增强版插件管理器
 */
export class EnhancedPlugins extends Plugins {
  private lifecycleManager: PluginLifecycleManager;
  private monitor: PluginMonitor;
  private testResults: Map<string, any> = new Map();

  constructor(options?: any) {
    super(options);
    this.lifecycleManager = new PluginLifecycleManager();
    this.monitor = new PluginMonitor();
    this.setupEventListeners();
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners(): void {
    // 监听性能警告
    this.monitor.on('performanceWarning', (metrics) => {
      Logger.warn(`Performance warning for plugin ${metrics.pluginId}:`, metrics);
    });

    // 监听方法错误
    this.monitor.on('methodError', (metrics) => {
      Logger.error(`Method error for plugin ${metrics.pluginId}:`, metrics);
    });

    // 监听生命周期状态变化
    this.lifecycleManager.on('stateChanged', (pluginId, newState, oldState) => {
      Logger.info(`Plugin ${pluginId} state: ${oldState} -> ${newState}`);
    });
  }

  /**
   * 增强版插件导入
   */
  async importEnhanced(
    pluginFilePath: string | null,
    jscode: string | null,
    options?: PluginImportOptions,
  ): Promise<any> {
    let pluginId = '';
    const startTime = Date.now();

    try {
      // 预验证阶段
      if (jscode) {
        PluginValidator.validateSecurity(jscode);
      }

      // 编译和验证插件
      const { PluginClass, code } = await this.checkout(jscode || '', options);
      pluginId = PluginClass.ID;

      // 设置加载状态
      this.lifecycleManager.setPluginState(pluginId, PluginState.LOADING);
      
      // 执行生命周期钩子
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.BEFORE_LOAD,
        pluginId,
        PluginClass,
      );

      // 完整验证
      PluginValidator.validate(PluginClass, code);

      // 调用原始导入方法
      const instance = await super.import(pluginFilePath, jscode, options);

      // 记录加载时间
      const loadTime = Date.now() - startTime;
      this.lifecycleManager.recordLoadTime(pluginId, loadTime);

      // 设置已加载状态
      this.lifecycleManager.setPluginState(pluginId, PluginState.LOADED);

      // 如果启用了插件，设置为启用状态
      if (options?.enable) {
        this.lifecycleManager.setPluginState(pluginId, PluginState.ENABLED);
      }

      // 执行加载后钩子
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.AFTER_LOAD,
        pluginId,
        PluginClass,
      );

      // 为插件方法添加监控代理
      this.addMonitoringToPlugin(pluginId, instance);

      Logger.info(`Plugin ${pluginId} loaded successfully in ${loadTime}ms`);
      return instance;

    } catch (error) {
      if (pluginId) {
        this.lifecycleManager.setPluginState(pluginId, PluginState.ERROR);
        this.lifecycleManager.recordError(pluginId, error as Error);
      }
      throw error;
    }
  }

  /**
   * 为插件实例添加监控代理
   */
  private addMonitoringToPlugin(pluginId: string, instance: any): void {
    const methodNames = Object.getOwnPropertyNames(Object.getPrototypeOf(instance))
      .filter(name => typeof instance[name] === 'function' && name !== 'constructor');

    for (const methodName of methodNames) {
      const originalMethod = instance[methodName];
      instance[methodName] = this.monitor.createMethodProxy(
        pluginId,
        methodName,
        originalMethod.bind(instance),
      );
    }
  }

  /**
   * 增强版启用插件
   */
  async enableEnhanced(id: string): Promise<void> {
    try {
      this.lifecycleManager.setPluginState(id, PluginState.ENABLING);
      
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.BEFORE_ENABLE,
        id,
      );

      await super.enable(id);

      this.lifecycleManager.setPluginState(id, PluginState.ENABLED);
      
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.AFTER_ENABLE,
        id,
      );

      Logger.info(`Plugin ${id} enabled successfully`);
    } catch (error) {
      this.lifecycleManager.setPluginState(id, PluginState.ERROR);
      this.lifecycleManager.recordError(id, error as Error);
      throw error;
    }
  }

  /**
   * 增强版禁用插件
   */
  async disableEnhanced(id: string): Promise<void> {
    try {
      this.lifecycleManager.setPluginState(id, PluginState.DISABLING);
      
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.BEFORE_DISABLE,
        id,
      );

      await super.disable(id);

      this.lifecycleManager.setPluginState(id, PluginState.DISABLED);
      
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.AFTER_DISABLE,
        id,
      );

      Logger.info(`Plugin ${id} disabled successfully`);
    } catch (error) {
      this.lifecycleManager.setPluginState(id, PluginState.ERROR);
      this.lifecycleManager.recordError(id, error as Error);
      throw error;
    }
  }

  /**
   * 测试插件
   */
  async testPlugin(pluginId: string, testConfig?: any): Promise<any> {
    try {
      const plugin = this.getPluginById(pluginId);
      if (!plugin) {
        throw new Error(`Plugin ${pluginId} not found`);
      }

      const { props, instance } = plugin;
      if (!instance) {
        throw new Error(`Plugin ${pluginId} is not enabled`);
      }

      Logger.info(`Starting tests for plugin ${pluginId}`);
      
      const testResult = await TTSTestFramework.runPluginTests(
        props as PluginInterface,
        instance,
        testConfig,
      );

      this.testResults.set(pluginId, testResult);
      
      Logger.info(`Plugin ${pluginId} tests completed: ${testResult.passedTests}/${testResult.totalTests} passed`);
      
      return testResult;
    } catch (error) {
      Logger.error(`Plugin ${pluginId} test failed:`, error);
      throw error;
    }
  }

  /**
   * 获取插件性能报告
   */
  getPluginPerformanceReport(pluginId?: string): any {
    if (pluginId) {
      return {
        stats: this.monitor.getPluginStats(pluginId),
        state: this.lifecycleManager.getPluginState(pluginId),
        loadTime: this.lifecycleManager.getLoadTime(pluginId),
        errors: this.lifecycleManager.getErrors(pluginId),
        testResults: this.testResults.get(pluginId),
      };
    }

    return {
      performance: this.monitor.getPerformanceReport(),
      lifecycle: this.lifecycleManager.getStatsSnapshot(),
      testResults: Object.fromEntries(this.testResults),
    };
  }

  /**
   * 清理插件数据
   */
  async deleteEnhanced(id: string): Promise<void> {
    try {
      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.BEFORE_UNLOAD,
        id,
      );

      await super.delete(id);

      // 清理相关数据
      this.lifecycleManager.cleanup(id);
      this.monitor.clearPluginMetrics(id);
      this.testResults.delete(id);

      await this.lifecycleManager.executeLifecycleHook(
        PluginLifecycleEvent.AFTER_UNLOAD,
        id,
      );

      Logger.info(`Plugin ${id} deleted successfully`);
    } catch (error) {
      this.lifecycleManager.recordError(id, error as Error);
      throw error;
    }
  }
}